package com.cqeec.waimai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqeec.waimai.common.CustomException;
import com.cqeec.waimai.dto.SetmealDto;
import com.cqeec.waimai.entity.Setmeal;
import com.cqeec.waimai.entity.SetmealDish;
import com.cqeec.waimai.mapper.SetmealMapper;
import com.cqeec.waimai.service.SetmealDishService;
import com.cqeec.waimai.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    SetmealDishService setmealDishService;
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
//        先保存setmeal 表的数据
        this.save(setmealDto);
//        再保存 setmeal_dish 表数据
        List<SetmealDish> list = setmealDto.getSetmealDishes();
        list.forEach(x->x.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(list);
    }

    @Override
    @Transactional
    public void deleteById(List<Long> ids) {
//        查询套餐状态，判断是否可以删除
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,ids);
        wrapper.eq(Setmeal::getStatus,1);
        int count = this.count(wrapper);
        if (count>1){
            throw new CustomException("套餐正在售卖，无法删除！");
        }
//        可以删除套餐情况
//        先删除套餐表的数据
        this.removeByIds(ids);
//        删除套餐相关表的数据 setmeal_dish 表中的数据
        LambdaQueryWrapper<SetmealDish> wrapper1=new LambdaQueryWrapper<>();
//        根据套餐的id删除 setmeal_dish 表的数据
        wrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(wrapper1);
    }
}
